import { ActionType, EditableFormInstance, EditableProTable, heILIntl, ProCard, ProColumns, ProForm, ProFormInstance, ProTable } from "@ant-design/pro-components";
import { Button, Card, Checkbox, Col, Flex, FormInstance, Input, message, Row, Space, Table, TableColumnProps, TableColumnsType, TableColumnType, Tabs, Tag } from "antd";
import { TabsProps }  from 'antd';
import {Splitter} from "antd";
import { useRef, useState } from "react";
import { s_getcommontableinfo, s_updateInfo, status2text } from "@/services/basis";
import { useModel } from "@umijs/max";


const App:React.FC=()=>{
    const [selectedRole,setSelectedRole]=useState<DataType[]>([]);
    const [expandKeys,setExpandKeys]=useState<any[]>([]);
    const [dataSource,setDataSource]=useState([]);

    const {initialState}=useModel('@@initialState');
    const x_id=initialState?.currentUser?.x_id;

    // 权限表单+表格
    const table_ref=useRef<ActionType>();
    const form_ref=useRef<ProFormInstance>();
    const editable_ref=useRef<EditableFormInstance>();

   //角色列表定义 
    interface DataType{
        id:number,
        code:string,
        name:string,
        status:number,
        modifyat?:string,
        mofifyuser?:string,
    }

    const columns:ProColumns<DataType>[]=[
        { key:'id',dataIndex:'id',title:'ID',hidden:true},
        { key:'code', dataIndex:'code',title:'编码', },
        { dataIndex:'name', title:'角色名称',},
        { dataIndex:'status',title:'状态',
             render:(text:any)=>text==1?<Tag>正常</Tag>:text==2?<Tag color="blue">冻结</Tag>:<Tag color="red">删除</Tag>,
        }
    ];
  
     interface DataType2{
        rid:number,
        id:number,
        model:string,name:string,
        ischeck:string[],
        dsc:string,
        // children:any,
        isend:number,level:number,
     }

     const columns2:ProColumns<DataType2>[]=[
       {dataIndex:'rid',title:'rid',editable:false,hidden:true,},
       {dataIndex:'id',title:'id',editable:false,hidden:true,},
       {dataIndex:'model',title:'模块',editable:false},
       {dataIndex:'name',title:'名称',editable:false,hidden:true,},
       {dataIndex:'dsc',title:'功能名称',editable:false},
       {dataIndex:'isend',hidden:true},
       {dataIndex:'level',hidden:true},
      //  {dataIndex:'children',title:'操作',editable:false},
       {dataIndex:'ischeck',title:'选择',
           valueType:'checkbox',valueEnum:{"1":{text:'OK'}},
      }
     ];


            
    // interface Dt{
    //     id:number,
    //     status:string[],
    //     // status:number[],
    //   }

    //  const col:ProColumns<Dt>[]=[
    //     {dataIndex:'id',title:'ID'},
    //     {dataIndex:'status',title:'状态',
    //         valueType:'checkbox',
    //         // valueEnum:{"1":{text:'选中'}},
    //         valueEnum:{'1':{text:'选中'}},
    //      },
    //  ]

    //  const da:Dt[]=[
    
    //      {id:1,status:['1']},
    //     {id:2,status:['']},
    //     {id:3,status:['1']},
    //     {id:4,status:['']}
    //   ]
const items:TabsProps['items']=[
      {  key:'grant',
         label:'操作权限',
         children:<>
<ProForm formRef={form_ref}  submitter={false}
           initialValues={{table_grant:[]}}
        >
            {/* {JSON.stringify(dataSource)} */}
            右侧增加单据列明细。当左侧选择单据后，右侧自动跳出单据明细项，可勾选即授权。
            <EditableProTable<DataType2>
               search={false}
               name='tablegrant'
               rowKey='rid'
               editableFormRef={editable_ref}
               actionRef={table_ref}
               columns={columns2}
              //  dataSource={dataSource}
               editable={{
                    type:'multiple',
                    // editableKeys:[1,2,3,4,5,6,7]
                    
               }}

               expandable={{
                   defaultExpandAllRows:true,
                   expandedRowKeys:expandKeys,
              }}
              recordCreatorProps={false}
            />
            </ProForm>  
           </>
      },
      {
        key:'data',
        label:'数据权限',
        children:<>
           数据权限分配,包括：供应商、客户、部门、业务员、仓库
        </>
      }
    ];

      //保存授权
      async function saveGrant(){
        if(selectedRole.length==0)
          message.warning('没有选中角色并授权，不能保存');
        else{
        const fdata=form_ref.current?.getFieldValue('tablegrant');
        const route=fdata.filter((item:any)=>item.ischeck&&item.ischeck.length>0).map((item2:any)=>item2.name);
        var operate:any[]=[];
        fdata.map((item:any)=>{
              if(item.children)
                item.children.map((item2:any)=>{
                     if(item2.ischeck&&item2.ischeck.length>0)
                     operate.push(item2.name);
                });
          });
          // source,x_id,operater_id,etype,fdata
           
          const x=await s_updateInfo({x_id,source:'grant',opeater_id:1,
                    fdata:{route,operate,role_id:selectedRole[0].id},
                  });
          if(x.success)
               message.success('保存成功');
          else
              message.error('保存失败，请联系管理员');
        }
      }


      //取消授权
      function resetGrant(){
        table_ref.current?.reset?.();
      }

// 以下为表单区=======================================================================================================
    return(
        <>
        <Row gutter={8}>
            <Col span={8}>
            <ProCard style={{height:700,overflow:'auto'}} title='角色列表' 
              //  extra={<Space><Button>按角色授权</Button></Space>}
               >
                 {/* {'当前选中的角色ID：'+JSON.stringify(selectedRole)} */}
                <ProTable<DataType>  
                   search={false}
                   columns={columns}   
                   rowSelection={{
                        type:'radio',
                        async onChange(selectedRowKeys:any, selectedRows:any, info) {
                            setSelectedRole(selectedRows);
                            // 按角色获取已授权的菜单列表
                            const x=await s_getcommontableinfo({x_id,source:'v_grantlist',
                                  fdata:{role_id:selectedRowKeys[0]}});
                            //   alert(JSON.stringify(x.data[0]));
                            setDataSource(x.data[0]);
                             const data=x.data[0];
                            //  alert(JSON.stringify(data));
                             
                              
                            //  alert(Array.isArray(data));
                            //  form_ref.current?.setFieldValue('tablegrant',data);
                            // alert(JSON.stringify(data.map((item:any)=>item.id)));
                            const data2=data.map((item:any)=>({...item,
                                        children:item.children==null?null:JSON.parse(item.children)}));
                            // alert(JSON.stringify(data2)); 
                            // setDataSource(data2);
                            form_ref.current?.setFieldValue('tablegrant',data2);

                            //将children的rid也设置为可编辑
                            var rids:any[]=[];
                             data2.map((item:any)=>{
                                 rids.push(item.rid);
                                 var ch=item.children;
                                 if(ch!=null)
                                    ch.map((item2:any)=>{
                                       rids.push(item2.rid);
                                    });
                            });
                            
                            rids.map((item:any)=>{
                               table_ref.current?.startEditable(item);
                            });
                            //展开所有行
                            setExpandKeys(rids);
                            
                        },
                    }} 
                   rowKey='id'
                   request={async ()=>{
                      const x=await s_getcommontableinfo({x_id,source:'base_role',id:0});
                      return {
                        data:x.data[0],
                        success:true,
                      }
                    }}
                    />
            </ProCard>
            </Col> 
            
            <Col span={16}>
            <ProCard style={{height:700,overflow:'auto'}} title='权限列表' 
                // hoverable={true}
                extra={<Space>
                  <Button onClick={()=>saveGrant()}>保存</Button>
                  <Button onClick={()=>resetGrant()}>取消</Button>
                  {/* <Button onClick={()=>alert(JSON.stringify(editable_ref.current?.getRowsData?.()))}>权限数据</Button> */}
             </Space>} >
            {/* {JSON.stringify(dataSource2)} */}
                <Tabs items={items} />
        
            </ProCard>
            </Col>          
        </Row>
    
     </>
);
}

export default App;